package com.xiaohan.springbootinit.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaohan.springbootinit.common.ErrorCode;
import com.xiaohan.springbootinit.exception.BusinessException;
import com.xiaohan.springbootinit.model.entity.Image;
import com.xiaohan.springbootinit.service.ImageService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

/**
 * @program: hanso-backend
 * @description: 图片接口实现类
 * @author: 韩小豪
 * @create: 2025-04-17 19:12
 **/

@Service
public class ImageServiceImpl implements ImageService {
	@Override
	public Page<Image> searchImage(String searchText, long pageNum, long pageSize) {
		/**
		 * 每页的第一张图片下标
		 * 假设要查2页，每页8条数据
		 * 第一页：0 - 7
		 * 第二页：8 - 15
		 * currentIndex = (pageNum - 1) * pageSize;
		 */
		long currentIndex = (pageNum - 1) * pageSize;
		String url = String.format("https://cn.bing.com/images/search?q=%s&first=%d", searchText, currentIndex);
		Document doc;  //访问该url，获取页面内容
		try {
			doc = Jsoup
					.connect(url)
					.timeout(120000)  //bing访问较慢，时间设长点
					.get();
		} catch (IOException e) {
			throw new BusinessException(ErrorCode.SYSTEM_ERROR, "图片数据获取异常，请稍后重试...");
		}

		//通过类选择器筛选出所有图片元素
		Elements elements = doc.select(".iuscp.isv");
		//遍历获取图片对象
		ArrayList<Image> images = new ArrayList<>();
		for (Element element : elements) {

			// 获取图片地址 murl
			String m = element.select(".iusc").attr("m");
			Map<String, Object> rsMap = JSONUtil.toBean(m, Map.class);
			String mUrl = (String) rsMap.get("murl");
//			System.out.println(mUrl);

			// 获取图片标题
			String title = element.select(".inflnk").attr("aria-label");
//			System.out.println(title+"\n");
//			System.out.println(element);

			Image rsImage = new Image();
			rsImage.setMUrl(mUrl);
			rsImage.setTitle(title);
			images.add(rsImage);

			//当前页面只展示pageSize条数据
			if(images.size() >= pageSize) break;
		}
		//测试
//		System.out.println(doc);  //输出获取的文档内容
//		System.out.println(images);

		//将list对象转为page对象
		Page<Image> imagePage = new Page<>(currentIndex, pageSize);
		imagePage.setRecords(images);
		return imagePage;
	}
}
